<?php

namespace app\common\controller;

use app\common\enum\ResponseCode;
use app\common\models\User;
use app\common\models\UserToken;

class BaseApi extends Api
{
    protected $model = null;
    protected $require = [];
    protected $validate = [];
    protected $selectable = [];
    protected $data = [];
    protected $userId = 0;
    protected $userData = [];
    protected $httpUrl = '';

    /**
     * post 方式请求
     */
    protected function isPost()
    {
        if (!request()->isPost()) $this->jsonFail('请使用POST请求');
    }

    /**
     * get 方式请求
     */
    protected function isGet()
    {
        if (!request()->isGet()) $this->jsonFail('请使用GET请求');
    }

    /**
     * json 数据流处理
     * @param array $param
     * @param string $request post param
     */
    protected function verifyParam($param = [], $request = 'post')
    {
        if ($request == 'post'){
            $this->isPost();
            $post_data = request()->post();
        }else{
            $this->isGet();
            $post_data = request()->param();
        }
        if (!empty($param)){
            $this->require = $param;
        }
        if (!empty($this->require)){
            if (is_string($this->require)){
                $this->require = explode(',', $this->require);
            }
        }
        if (!empty($this->selectable)){
            if (is_string($this->selectable)){
                $this->selectable = explode(',', $this->selectable);
            }
        }
        if (!empty($this->require) || !empty($this->selectable)){
            if (empty($this->selectable)){
                $param = $this->require;
            }else{
                $param = array_merge($this->require, $this->selectable);
            }
            $array_keys = array_keys($post_data);
            foreach ($array_keys as $key) {
                if (!in_array($key, $param)){
                    unset($post_data[$key]);
                }
            }
            if (!empty($this->require)){
                foreach ($this->require as $val){
                    if (!isset($post_data[$val]) || $post_data[$val] === ''){
                        if (!empty($this->validate[$val])){
                            $error_msg = $this->validate[$val];
                        }else{
                            $error_msg = '缺少请求参数：' . $val;
                        }
                        $this->jsonFail($error_msg);
                    }
                }
            }
            $this->data = $post_data;
            // 是否保存记录参数信息
            if (env('app_debug')){
                $this->consoleLog($this->data);
            }
        }
    }

    public function verifyToken($require = true)
    {
        $token = request()->header('token');
        if (empty($token)){
            if ($require){
                $this->jsonFail('缺少请求头token');
            }
        }
        $user_token = new UserToken();
        // 特殊验证机制
        if (strpos($token, $user_token::APP_AUTH) !== false){
            $user_id = $user_token->appAuthSha($token);
        }else{
            $user_id = $user_token->tokenAuth($token);
        }
        if (empty($user_id)){
            if ($require){
                $this->jsonTokenFailed('系统检测到您长时间未登陆，请重新登录');
            }
        }else{
            // 获取用户信息
            $user_fields = 'user_id,mobile,user_name';
            $user_model = new User();
            $user_data = $user_model->getFind($user_id, $user_fields);
            if (empty($user_data)){
                if ($require) {
                    $this->jsonTokenFailed('系统检测到您长时间未登陆，请重新登录');
                }
            }else{
                $this->data['user_id'] = $user_data['user_id'];
                $this->userId = $user_data['user_id'];
                $this->userData = $user_data;
            }
        }
    }

    /**
     * @param int $limit 截取数量
     * @return string
     */
    protected function getApiPage($limit = 10)
    {
        // 分页
        $firstRow = 0; // 开始截取
        $nowPage = empty($this->data['page'])? 1 : $this->data['page']; // 当前页码
        if ($nowPage > 1){
            $firstRow = $limit*($nowPage-1);
        }
        return  $firstRow . ',' .  $limit;
    }

    /**
     * 请求验证失败
     * status 9999：请求验证失败
     * @param string $message
     * @param array $data
     */
    protected function jsonFail($message = '')
    {
        $this->error($message, null, ResponseCode::FORBIDDEN);
    }

    /**
     * 操作数据成功
     * @param string $message
     */
    protected function jsonSuccess($message = '', $data = null)
    {
        $this->success($message, $data, ResponseCode::SUCCESS);
    }

    /**
     * 操作数据失败
     * @param string $message
     * @param array $data
     */
    protected function jsonError($message = '', $data = null)
    {
        $this->success($message, $data, ResponseCode::PARAM_ERR);
    }

    /**
     * 获取数据成功；肯定有数据返回对象数组形式
     * @param array $data
     * @param string $message
     */
    protected function jsonResult($data = [], $message = '')
    {
        $this->success($message, $data, ResponseCode::SUCCESS);
    }

    /**
     * 没有更多数据
     * status 1001：没有更多数据；空对象数组数据
     * @param array $data
     * @param string $message
     */
    protected function jsonEmpty($message = '')
    {
        $this->success($message, null, ResponseCode::SUCCESS);
    }

    /**
     * TOKEN失效
     * @param string $message
     */
    protected function jsonTokenFailed($message = '')
    {
        $this->error($message, null, ResponseCode::UNAUTH);
    }

    /**
     * 数据日志保存
     * @param $data
     * @param $type
     * @param int $flags
     */
    protected function consoleLog($data, $type = '', $flags = FILE_APPEND)
    {
        $dir = getcwd() . '/api_log/';
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $html = '';
        $filename = $dir . $type . date('YmdH') . '.html';
        if (!file_exists($filename)){
            $html .= '<!DOCTYPE html><html><head>';
            $html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
            $html .= '</head><body>';
        }
        $html .= '<div style="display: inline-block;margin-left: 35%">';
        $html .= '<h5 style="margin: 5px 0">---------------------------------------------------------------</h5>';
        $html .= '<h5 style="margin: 5px 0">执行日期：' . date('Y-m-d H:i:s', NEW_TIME) . '</h5>';
        $html .= '<h5 style="margin: 5px 0">请求地址：<textarea style="display: inline-block;width: 100%;border: none;font-size: 14px;font-weight: bold;font-family: bold;">' . $this->httpUrl . request()->url() . '</textarea></h5>';
        $html .= '<h5 style="margin: 5px 0">数据信息：<textarea style="display: inline-block;width: 100%;border: none;font-size: 14px;font-weight: bold;font-family: bold;">' . json_encode($data) . '</textarea></h5>';
        $html .= '</div>';
        if (!file_exists($filename)){
            $html .= '</body></html>';
        }
        file_put_contents($filename , $html, $flags);
    }

}